package console

import (
	"gitee.com/dark.H/dark"
	termbox "github.com/nsf/termbox-go"
)

func OnInput(panelLoc *PanelLoc, doSomeKey func(input dark.Str, key termbox.Event)) (typedStr dark.Str, cancel bool) {
	if panelLoc == nil {
		panic("must have a paneloc !")
	}
	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	panelLoc.Cusor().ShowCursor().Print()
	offset := 0
	decorateEnd := dark.Str("")
LOOP:
	for {

		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			switch ev.Key {

			case K_DEL:
				if len(typedStr) > 0 {
					typedStr = typedStr[:typedStr.Len()-1]
					offset -= 1
					decorateEnd += " " + decorateEnd.ANSI(dark.ANSI_COLUMN_LEFT, 1)
				}

			case termbox.KeyArrowLeft:
				if offset > 0 {
					decorateEnd += decorateEnd.ANSI(dark.ANSI_COLUMN_LEFT, 1)
					offset -= 1
				}

			case termbox.KeyArrowRight:
				if offset < typedStr.Len() {
					decorateEnd += decorateEnd.ANSI(dark.ANSI_COLUMN_RIGHT, 1)
					offset += 1

				}

			case termbox.KeyCtrlA:
				// typedStr += typedStr.ANSI(dark.ANSI_COLUMN_LEFT, 2)
				// panelLoc.Label(dark.S("col: ")+dark.S(panelLoc.X)+dark.S("offset :")+dark.S(offset), -1)
				// panelLoc.X -= (offset - 1)
				decorateEnd = dark.Str("").ANSI(dark.ANSI_COLUMN_LEFT, offset)
				offset = 0
			case termbox.KeyCtrlE:

				decorateEnd = dark.Str("")
				offset = typedStr.Len()

				// fmt.Println(typedStr)
			case K_CTRL_C, termbox.KeyEsc:
				panelLoc.HiddenCursor().Print(true)
				cancel = true
				break LOOP
			case termbox.KeyTab:
				typedStr = typedStr[:offset] + dark.Str("\t") + typedStr[offset:]

				offset += 1
			case termbox.KeySpace:
				typedStr = typedStr[:offset] + dark.Str(" ") + typedStr[offset:]
				offset += 1
			case termbox.KeyEnter:
				break LOOP
			default:

				typedStr = typedStr[:offset] + dark.Str(ev.Ch) + typedStr[offset:]
				offset += 1

				// panelLoc.Label(dark.S(ev), -1)
			}

			doSomeKey(typedStr, ev)
			panelLoc.Cusor().A(typedStr).A(decorateEnd).Printline(true)

		}
	}
	return
}

func InputLastLine() dark.Str {
	res, _ := OnInput(&PanelLoc{
		Y: -1,
		X: 1,
	}, func(input dark.Str, key termbox.Event) {

	})
	return res
}
